package com.quick.develop.flowable.application.impl;

import com.quick.develop.flowable.domain.dto.model.BpmModelElementsDTO;
import com.quick.develop.flowable.application.IBpmModelApplication;
import com.quick.develop.flowable.framework.convert.model.BpmModelElementsConvert;
import com.quick.develop.flowable.utils.FlowableUtil;
import com.quick.develop.flowable.service.definition.IBpmProcessDefinitionService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.CallActivity;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author junyuan.liu
 * @description: 
 * @date 2022/5/18 13:27
 */
@Component
@Slf4j
public class BpmModelApplicationImpl implements IBpmModelApplication {
    @Resource
    IBpmProcessDefinitionService bpmProcessDefinitionService;

    @Override
    public List<BpmModelElementsDTO> getModelElementsByProcessDefinitionKey(String key) {
        ProcessDefinition definition = bpmProcessDefinitionService.getActiveProcessDefinitionByKey(key);
        return Optional.ofNullable(definition).map(d -> this.getModelElements(d.getId())).orElse(Collections.emptyList());
    }

    @Override
    public List<BpmModelElementsDTO> getModelElementsByProcessDefinitionId(String id) {
        ProcessDefinition definition = bpmProcessDefinitionService.getProcessDefinition(id);
        return Optional.ofNullable(definition).map(d -> this.getModelElements(d.getId())).orElse(Collections.emptyList());
    }
    
    private List<BpmModelElementsDTO> getModelElements(String processDefinitionId){
        BpmnModel bpmnModel = bpmProcessDefinitionService.getBpmnModelByDefinitionId(processDefinitionId);
        List<UserTask> userTasks = FlowableUtil.getBpmnModelElements(bpmnModel, UserTask.class);
        List<CallActivity> activities = FlowableUtil.getBpmnModelElements(bpmnModel, CallActivity.class);

        return BpmModelElementsConvert.INSTANCE.convertList(userTasks, activities);
    }
}
